<template>
  <div id="container">
    <input v-model="keyword" id="keyword" placeholder="请输入搜索位置" autocomplete="off" @keyup.enter="searchPlace" />
    <div>
      <p>经度: {{ longitude }}</p>
      <p>纬度: {{ latitude }}</p>
      <p>{{ message }}</p>
    </div>
    <div v-if="places.length">
      <h3>搜索结果:</h3>
      <ul class="results">
        <li v-for="place in places" :key="place.id" @click="selectPlace(place)">{{ place.name }}</li>
      </ul>
    </div>
    <van-button @click="city" class="btn" type="primary">确定</van-button>
  </div>
</template>

<script setup>
import { ref, onMounted, defineProps, watch } from 'vue'
import AMapLoader from '@amap/amap-jsapi-loader'
import { useRouter } from 'vue-router';
const router = useRouter();
const props = defineProps({
  message: String
})

const keyword = ref('')
const longitude = ref(null)
const latitude = ref(null)
const places = ref([]) // 存储搜索结果
const emit = defineEmits(['update:longitude', 'update:latitude', 'update:address', 'childEvent'])
let map
let marker // 定义标记变量

const initMap = () => {
  AMapLoader.load({
    key: '5c1ffebbe0fe1382845a5a0329b03f67',
    version: '1.4.15',
    plugins: ['AMap.Autocomplete', 'AMap.PlaceSearch', 'AMap.Geocoder']
  }).then((AMap) => {
    map = new AMap.Map('container', {
      resizeEnable: true,
      zoom: 10,
      center: [116.397428, 39.90923]
    })
    emit('childEvent', 'Hello from Child!')
    AMap.plugin('AMap.ControlBar', function () {
      const controlBar = new AMap.ControlBar({
        showZoomBar: true, // 显示缩放条
        showControlButton: true // 显示控制按钮
      })
      map.addControl(controlBar)
    })
    map.on('click', async (e) => {
      longitude.value = e.lnglat.lng
      latitude.value = e.lnglat.lat
      emit('longitudeLi', longitude.value)
      emit('latitudeLi', latitude.value)
      console.log('经度:', longitude.value)
      console.log('纬度:', latitude.value)
      const apiKey = 'be64c3933f21b1cf456735c678152f48'
      const url = `https://restapi.amap.com/v3/geocode/regeo?key=${apiKey}&location=${longitude.value},${latitude.value}`
      try {
        const response = await fetch(url)
        const data = await response.json()

        if (data.status === '1') {
          const address = data.regeocode.formatted_address
          emit('addressLi', address)
          console.log(address)
        }
      } catch (error) {
        console.error('请求错误:', error)
      }
    })
  }).catch((error) => {
    console.error('加载 AMap 失败:', error)
  })
}


// 搜索地点
const searchPlace = async () => {
  const apiKey = 'be64c3933f21b1cf456735c678152f48'
  const url = `https://restapi.amap.com/v3/place/text?keywords=${encodeURIComponent(keyword.value)}&key=${apiKey}&extensions=all`

  try {
    const response = await fetch(url)
    const data = await response.json()
    if (data.status === '1') {
      places.value = data.pois // 存储搜索结果
    } else {
      console.error('搜索失败:', data.info)
      places.value = []
    }
  } catch (error) {
    console.error('请求错误:', error)
  }
}

// 选择搜索的地点
const dz = ref('')
const selectPlace = (place) => {
  longitude.value = place.location.split(',')[0]
  latitude.value = place.location.split(',')[1]
  emit('longitudeLi', longitude.value)
  emit('latitudeLi', latitude.value)
  dz.value = place.name
  // 在地图上添加标记
  if (marker) {
    marker.setMap(null) // 如果已存在标记，则移除
  }

  marker = new AMap.Marker({
    position: [longitude.value, latitude.value], // 设置标记的位置
    title: place.name // 设置标记的标题
  });

  marker.setMap(map); // 将标记添加到地图上
  console.log(`选择地点: ${place.name}, 经度: ${longitude.value}, 纬度: ${latitude.value}`)
}

// 在组件挂载后初始化地图

watch(keyword, (newVal) => {
  if (!newVal) {
    places.value = []; // 清空搜索结果
  }
});
const zoomIn = () => {
  map.setZoom(map.getZoom() + 1)
}

const zoomOut = () => {
  map.setZoom(map.getZoom() - 1)
}
onMounted(initMap)


const city = () => {
  console.log(dz,'asdfg')
  router.push({
    path: '/dizhi1',
    query: {city: dz.value}
  })
}



</script>



<style scoped>
#container {
  padding: 0;
  margin: 0;
  width: 100%;
  height: 376px;
}

.btn {
  position: fixed;
  bottom: 70px;
  width: 90%;
  margin: 0 5%;
  border-radius: 20px;
}


#keyword {
  margin-top: 3px;
  height: 30px;
  position: absolute;
  z-index: 999999;
  border-radius: 10px;
  border: none;
  font-size: 16px;
  width: 80%;
  border: 1px solid #ccc;
  height: 35px;
}

/* 自定义按钮样式 */
button {
  margin-top: 10px;
  padding: 5px 10px;
}

.results {
  position: absolute;
  top: 30px;
  /* 根据需要调整 */
  left: 0;
  right: 0;
  z-index: 1000;
  /* 确保在地图之上 */
  background-color: white;
  /* 设定背景颜色 */
  border: 1px solid #ccc;
  /* 可选的边框 */
  width: 150px;
  overflow-y: scroll;

}
</style>